package com.runvp.rest.app;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.annotation.Log;
import com.runvp.common.core.controller.BaseController;
import com.runvp.common.core.domain.AjaxResult;
import com.runvp.common.enums.BusinessType;
import com.runvp.common.enums.DataSource;
import com.runvp.common.enums.PayChannel;
import com.runvp.common.enums.PayPlat;
import com.runvp.common.model.vo.app.BizCreateOrderVO;
import com.runvp.common.model.vo.order.BizOrderOutEndVO;
import com.runvp.service.app.AppClientService;
import com.runvp.service.biz.domain.BizOrder;
import com.runvp.service.out.OutHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/app/main/order")
public class OrderAppController extends BaseController {

    @Autowired
    private AppClientService appClientService;
    @Autowired
    private OutHandler outHandler;

    /**
     * 订单创建
     */
    @Log(title = "订单创建", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody BizCreateOrderVO createOrderVO) {
        //app使用默认用户
        createOrderVO.setCustomerId(1L);
        if(StringUtils.isBlank(createOrderVO.getPayPlat())){
            createOrderVO.setPayPlat(PayPlat.PAY_QR_ALIPAY.getCode());
        }
        createOrderVO.setSource(DataSource.ANDROID.getCode());
        log.info("createOrder:::req: {}", JSONObject.toJSONString(createOrderVO));
        Map<String, Object> map;
        try {
            map = appClientService.createOrder(createOrderVO);
            if (PayChannel.PAY_SCORE.getCode().equals(createOrderVO.getPayChannel())) {
                BizOrder order = (BizOrder) map.get("order");
                outHandler.executeOut(order, order.getAmount());
                map.remove("order");
            }
        } catch (Exception e) {
            log.error("支付渠道【{}】创建订单失败:{}", createOrderVO.getPayChannel(), e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(map);
    }
    /**
     * 订单充电结束
     */
    @Log(title = "订单充电结束", businessType = BusinessType.INSERT)
    @PostMapping("/out/end")
    public AjaxResult outEnd(@RequestBody BizOrderOutEndVO endVO) {
        appClientService.outEnd(endVO);
        return AjaxResult.success();
    }



}
